<template>
  <div class="app-container">
    <form-json
      ref="formRef"
      v-if="Object.keys(formDataJson).length > 0"
      :form-json="formDataJson"
      :task="task"
      @form-change="handleFormChange"
    />
    <TaskOpinionDialog
      v-if="editDialog.visible"
      v-model="editDialog.visible"
      :title="editDialog.title"
      @submitForm="handleComfire"
    />
  </div>
</template>
<script lang="ts" setup>
import { type PropType, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { routerUtil, type DialogRef } from "jmash-core";
import { useI18n } from "vue-i18n";
import {
  formDefApi,
  nodeButtonApi,
  formDataApi,
  formFileApi,
  type NodeButtonModel,
} from "xyvcard-workflow";
import type { FlowTaskModel } from "@/api/flow/task/types";
import { BoolAny, StringAny } from "@/util/protobuf";
import formJson from "../FormJson/index.vue";

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const formRef = ref();
const emits = defineEmits([
  "nodeButtonList",
  "dealWith",
  "transfer",
  "delegate",
  "resolve",
]);
const props = defineProps({
  task: {
    type: Object as PropType<FlowTaskModel>,
    default: () => {},
  },
});
// 表单文件
interface FormFile {
  // 文件分类
  fileSort?: string;
  // 文件ID
  fileId?: string;
  // 文件名称
  fileName?: string;
}
console.log(props.task);
const form = reactive({} as any);
const formDataJson = reactive({} as any);
const tempData = reactive({
  action: "true",
  taskId: props.task.id,
  requestId: Math.random() * 10 + "",
  vars: {},
  // 意见
  comment: "",
});
const nodeButtonList = ref<NodeButtonModel[]>([]);
//编辑Dialog
const editDialog = ref({
  title: t("task.comment"),
  visible: false,
} as DialogRef);

const buttonCode = ref<string>();

// 获取表单数据
function queryFormDef() {
  formDefApi.findById({ formId: props.task.formKey }).then(({ data }) => {
    console.log(JSON.parse(data.pcFormContent as string));
    const obj = JSON.parse(data.pcFormContent as string);
    Object.assign(formDataJson, obj);
    console.log(formDataJson);
    queryNodeButtonList();
  });
}

// 获取节点按钮
function queryNodeButtonList() {
  nodeButtonApi
    .findBtnList({
      nodeId: props.task.taskDefinitionKey,
      processKey: (props.task.processDefinitionId as string).substring(
        0,
        (props.task.processDefinitionId as string).indexOf(":"),
      ),
    })
    .then(({ data }) => {
      nodeButtonList.value = data.results;
      emits("nodeButtonList", data.results);
    });
}

function handleFormChange(val: any) {
  console.log(val);
  Object.assign(form, val);
}

// 修改表单信息
function updateFormData() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const formData = {
        requestId: tempData.requestId,
        formId: props.task.formKey,
        actionId: props.task.businessKey,
        businessKey: props.task.businessKey,
        applyFiles: [] as FormFile[],
        data: {} as any,
      };
      formDataJson?.components.forEach((item: any) => {
        if (item.type === "filepicker" && !item.readonly) {
          fileCreate(item, formData.applyFiles);
        } else if (item.type !== "filepicker" && !item.readonly) {
          formData.data[item.id] = new StringAny(
            String(form[item.id]) as string,
          );
        }
      });
      console.log(formData);
      formDataApi.formDataOut(formData).then((res) => {
        console.log(res);
        if (res.status === 200) {
          dealWithComplete();
        }
      });
    }
  });
}

// 最后一步确认回传 或者补全材料
function createFormFile() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      const tempFile = {
        requestId: Math.random() * 10 + "",
        actionId: props.task.businessKey,
        files: [] as FormFile[],
      };
      formDataJson?.components.forEach((item: any) => {
        if (item.type === "filepicker" && !item.readonly) {
          fileCreate(item, tempFile.files);
        }
      });
      formFileApi.create(tempFile).then((res) => {
        if (res.status === 200) {
          dealWithComplete();
        }
      });
    }
  });
}

/**
 * 根据按钮代码执行相应的操作
 *
 * @param {string} buttonCode - 按钮的代码，用于判断执行哪种操作
 * @returns {void} 无返回值
 */
function customButAction(code: string) {
  buttonCode.value = code;
  if (code === "DealWithOk") {
    dealWithOk();
  } else if (code === "DealWithRefuse") {
    dealWithRefuse();
  } else if (code === "DealWithByForm") {
    updateFormData();
  } else if (code === "DealWithByFile") {
    createFormFile();
  } else if (code === "DealWithEnd") {
    dealWithRefuse();
  } else if (code === "DealWith") {
    emits("dealWith");
  } else if (code === "Transfer") {
    emits("transfer");
  } else if (code === "Delegate") {
    emits("delegate");
  } else if (code === "Resolve") {
    emits("resolve");
  }
}

function fileCreate(item: any, tempFile: FormFile[]) {
  console.log(item);
  // 1. 获取并验证当前字段的文件列表
  const currentFiles = form[item.id] || [];
  const validFiles = currentFiles.filter((file: FormFile) => file.fileId);
  console.log("当前字段有效文件:", validFiles);
  // 2. 准备最终文件列表（保留原有tempFile内容）
  const finalFiles = [...tempFile];
  console.log("最终文件列表:", finalFiles);
  // 3. 处理当前字段的文件
  validFiles.forEach((file: FormFile) => {
    // 检查是否已存在相同fileSort和fileId的文件
    const isDuplicate = finalFiles.some(
      (f) => f.fileId === file.fileId && f.fileSort === item.id,
    );
    if (!isDuplicate) {
      finalFiles.push({
        fileSort: item.id, // 使用当前字段ID作为fileSort
        fileId: file.fileId,
        fileName: file.fileName,
      });
    }
  });
  console.log("合并后的完整文件列表:", finalFiles);
  // 4. 返回处理后的数组（如果需要替换原数组）
  // 注意：这里直接修改了传入的tempFile引用
  tempFile.length = 0;
  tempFile.push(...finalFiles);
  // 或者返回新数组（根据您的实际需求选择）
  return finalFiles;
}

//审核通过
function dealWithOk() {
  tempData.action = "true";
  (tempData.vars as any)["approved"] = new BoolAny(true);
  (tempData.vars as any)["ended"] = new BoolAny(false);
  dealWithComplete();
}

//审核拒绝
function dealWithRefuse() {
  editDialog.value.visible = true;
}

// 确认提交
function handleComfire(opinion: string) {
  console.log("....", buttonCode.value);
  tempData.comment = opinion;
  if (buttonCode.value === "DealWithRefuse") {
    tempData.action = "false";
    (tempData.vars as any)["ended"] = new BoolAny(false);
    (tempData.vars as any)["approved"] = new BoolAny(false);
  } else if (buttonCode.value === "DealWithEnd") {
    tempData.action = "false";
    (tempData.vars as any)["approved"] = new BoolAny(false);
    (tempData.vars as any)["ended"] = new BoolAny(true);
  }
  console.log(tempData);
  dealWithComplete();
}

/**
 * 处理表单提交完成逻辑
 */
function dealWithComplete() {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      formDataApi.create(tempData).then((res) => {
        console.log(res);
        if (res.status === 200) {
          routerUtil.closeTagView(route.fullPath, router, false);
        }
      });
    }
  });
}

queryFormDef();

defineExpose({
  customButAction,
});
</script>
